package org.bigdata.framework.admin.web.util;

import java.io.File;  
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;  
import javax.xml.transform.Transformer;  
import javax.xml.transform.sax.SAXTransformerFactory;  
import javax.xml.transform.sax.TransformerHandler;  
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;  
  
public class CreateXMLFile {  
  
  
    public static void main(String[] args) throws Exception {
    	List<String> list = new ArrayList<String>();
    	list.add("title");
    	list.add("summery");
    	list.add("keyword");
    	list.add("author");
    	List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
    	/*Map<String, Object> m = new HashMap<String, Object>();
    	for (int i = 0; i < 1; i++) {
    		m = new HashMap<String, Object>();
    		m.put("title", "title"+i);
    		m.put("summery", "summery"+i);
    		m.put("keyword", "INSERT INTO `dal_hymax`.`hymax_wei_xin_gong_zhong_hao` (`id`, `create_user_id`, `update_org_id`, `create_time`, `submit_time`, `create_org_id`, `version`, `data_source`, `update_time`, `classes_id`, `update_user_id`, `submit_org_id`, `submit_user_id`, `status`, `title`, `author`, `keywords`, `summary`, `xin_wen_zheng_wen`, `wx_lai_yuan`, `source_url`, `biaoqian`, `fl_hao`, `cai_ji_ri_qi`, `pdf`, `cover`, `date`, `sourceinfo`) VALUES ('3907775062853642', '1', '', '2018-05-26 22:57:16', '', '48', '1.0', '15', '', '43', '', '', '', '0', 'OneMap联盟成立，全球高精度地图领军企业联手打造行业标准', '', '', NULL, '', '', '', '2018-05-24', '/wxgzh/68bb7ce265e29f07378ae5214d0e0a07.pdf', '//upload/image/20180329/weixin.sogou.com/cover/c4f4699e212417256e59c003f8bdf00e.jpeg', '2018-05-24', '泰伯网');"+i);
    		m.put("author", "author"+i);
    		mapList.add(m);
    		if(i%10000==0){
    			System.out.println("==========="+i);
    		}
		}*/
    	
    	FileOutputStream out = new FileOutputStream(new File("E:/entity.xml"));
		TransformerHandler handler = CreateXMLFile.createXML(out);
        writeToXml(handler,mapList);
    	closeXml(handler,out);
        /*
        SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		 ReadXml xml =  new ReadXml("//entities/entity",3, false);
		//xpath = "//qks/qk";
		parser.parse("E:/entity.xml", xml);
        
       
        List<Map<String, String>> list2 = xml.list;
        FileUtils.show(list2);
        */
          
    }  
  
    @SuppressWarnings("resource")
	public static TransformerHandler createXML(FileOutputStream out) {
        try {
            // 创建工厂  
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            TransformerHandler handler = factory.newTransformerHandler();
            Transformer info = handler.getTransformer();
            // 是否自动添加额外的空白 
            info.setOutputProperty(OutputKeys.INDENT, "yes");
            // 设置字符编码  
            info.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            info.setOutputProperty(OutputKeys.VERSION, "1.0");
            // 保存创建的saxbooks.xml  
            //FileOutputStream out = new FileOutputStream(new File(path));
            StreamResult result = new StreamResult(out);
            handler.setResult(result);
            handler.startElement("", "", "entities", null);
           return handler;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void writeToXml(TransformerHandler handler,List<Map<String, Object>>mapList) {
    	try {
    		 // 开始xml  
            handler.startDocument();
            //AttributesImpl impl = new AttributesImpl();
            //impl.clear();
            for (int i = 0; i < mapList.size(); i++) {
            	//impl.clear(); //清空属性  
    			handler.startElement("", "", "entity", null);
    			Map<String, Object> map = mapList.get(i);
    			
    			for (String key : map.keySet()) {
//    				impl.clear();
    				handler.startElement("", "", key, null);
    				if(map.get(key)!=null && !"".equals(map.get(key))){
    					String value = map.get(key).toString();
    					value = stripNonValidXMLChars(value);
//    					value = value.replace("<", "<![CDATA[<]]>").replace(">", "<![CDATA[>]]>")
//    							.replace("&", "<![CDATA[&]]>").replace("\n", "<![CDATA[\n]]>").replace("\r", "<![CDATA[\r]]>");//
    					value = "<![CDATA[" + value +"]]>";
    					handler.characters(value.toCharArray(), 0, value.length()); //为title元素添加文本  
    				}else if("".equals(map.get(key))){
    					handler.characters(" ".toCharArray(), 0, " ".length()); //为title元素添加文本  
    				}
    				handler.endElement("", "", key);
				}
    			handler.endElement("", "", "entity");
    			if(i%10000==0){
    				System.out.println("本组数据正在写入xml进度："+i+"/"+mapList.size());
    			}
    		}
            System.out.println("本组数据正在写入xml进度："+mapList.size()+"/"+mapList.size());
            
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	public static String stripNonValidXMLChars(String str) {
		if (str == null || "".equals(str)) {
			return str;
		}
		StringBuffer s = new StringBuffer();
		char[] charArray = str.toCharArray();
		for (char c : charArray) {
			if (!(c < 0x9 || c > 0x9 && c < 0xA || c > 0xA && c < 0xD || c > 0xD && c  
					< 0x20 || c > 0xD7FF && c < 0xE000 || c > 0xFFFD)){//下面了允许的字符范围
				s.append(c);
				//s += c;
			}
		}
		return s.toString();
//		return str.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]+&*\\s*", "");
	}
    public static void closeXml(TransformerHandler handler,FileOutputStream out){
    	 try {
			handler.endElement("", "", "entities");
			handler.endDocument();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}  
